package com.javaking.clanteam.hvz;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.javaking.clanteam.hvz.sql.HVZUser;
import com.javaking.clanteam.hvz.sql.SQLRelay;
import com.javaking.clanteam.hvz.utils.BarcodeScanActivity;
import com.javaking.clanteam.hvz.utils.ModeratorApprovalActivity;

public class SignupActivity extends Activity {

    /** The Constant APPROVAL_NEEDED. Number is comletely arbitrary. */
    private static final int APPROVAL_NEEDED = 0x10;
	
	/** The barcode. */
	private String barcode;
    
    /** The query result. */
    private JSONObject queryResult;
    
    /** The failure. */
    private final int FAILURE = -1;
    
    /** The success. */
    private final int SUCCESS = 0;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
    }

    /**
     * Scan barcode.
     */
    public void scanBarcode(View v)
    {
    	Intent scanIntent = new Intent(this, BarcodeScanActivity.class);
    	startActivityForResult(scanIntent, 0);
    }
    
    /**
     * Scaning a barcode is returned. It might be that we needed this for approving a new mod.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// Check to make sure that it returned OK.
    	if(resultCode==RESULT_OK)
		{
	    	switch(requestCode) {
	    	case 0: // 0 is kinda my default, no real meaning
	    			// set the barcode the scan result.
		    	barcode = data.getStringExtra("barcode");
		    	TextView barcodeLabel = (TextView)findViewById(R.id.signup_barcodeLabel);
		    	barcodeLabel.setText("Barcode:"+barcode);
				break;
				
	    	case APPROVAL_NEEDED:
	    		// if this result 
	    		if (data.getBooleanExtra("approved", false)) addUserApproved();
	    		break;
	    	}
		}
    }
    
    /**
     * Called when we have confirmed that this player has permission to be created.
     */
    private void addUserApproved() {
    	try {
	    	HVZUser newUser = new HVZUser(); // This is the user that will be added.
	    	
	    	// Get some info about the stuff that the user entered.
			newUser.setUsername(((EditText)findViewById(R.id.usernameEditText)).getText().toString());
			newUser.setUsertype(((Spinner)findViewById(R.id.usertypeSpinner)).getSelectedItem().toString());
			newUser.setBarcode(barcode);
			
			// Call the add user function.
	    	queryResult = SQLRelay.addUser(newUser);
	    	
	    	// Call the appropriate show dialog function depending on the query result.
	    	if(queryResult.has("SUCCESS")) showDialog(SUCCESS);
	    	else showDialog(FAILURE);
    	} catch (Exception e) {
    		showDialog(FAILURE);
    	}
	}

	/**
	 * Called when the user clicks the 'add user' button. We need to get the data
	 * from the fields in the add user screen and query the server to add the user.
	 * <br/>
	 * If the user is a moderator, we need to ask for permission. 
	 */
	public void addUser(View v)
    {    	
		
		// First, we need to check if the user is going to be a mod,
		// if so, ask to scan a mod's barcode.
		if(((Spinner)findViewById(R.id.usertypeSpinner))
				.getSelectedItem().toString().equals("Moderator"))
		{
			Intent confirmModerator = new Intent(this,ModeratorApprovalActivity.class);
			startActivityForResult(confirmModerator, APPROVAL_NEEDED);
			return;
		}
		
		// Create and setup a user based off the info in the user screen.
    	HVZUser newUser = new HVZUser();
		newUser.setUsername(((EditText)findViewById(R.id.usernameEditText)).getText().toString());
		newUser.setUsertype(((Spinner)findViewById(R.id.usertypeSpinner)).getSelectedItem().toString());
		newUser.setBarcode(barcode);
    	
		// Query the server and show the appropriate dialog.
    	queryResult = SQLRelay.addUser(newUser);
    	if(queryResult.has("SUCCESS")) showDialog(SUCCESS);
    	else showDialog(FAILURE);
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog; // This is the dialog that will be returned.
    				   // It will be defined in one of the cases.
    	AlertDialog.Builder builder = new AlertDialog.Builder(this); // Builder will be used a lot.
    	switch (id)
    	{
    	case FAILURE: // Something failed.
    		
    		// Attempt to set the title based off the error text return from the server.
    		// if we can't get the text, say unknown error.
    		try {
				builder.setTitle("ERROR:"+queryResult.getString("ERROR"));
			} catch (JSONException e) {
				builder.setTitle("An unknown error occured");
				e.printStackTrace();
			}
    		
    		// :(
    		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
    		dialog = builder.create(); // create the dialog.
    		break;
    		
    	case SUCCESS: // We add the user.
    		// Set the title to an ok message.
    		builder.setTitle("User has been successfully added.");
    		
    		
    		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss(); // hide the dialog.
					
					// Now we need to change to the user actions view.
					Intent userIntent = new Intent(getApplicationContext(), UserActivity.class);
					HVZUser user = SQLRelay.readUser(barcode);
					userIntent.putExtra("HVZUser_string", user.toString());
					startActivity(userIntent);
					finish();
				}
			});
    		dialog = builder.create(); // create the dialog.
    		break;
    	default:
    		dialog=super.onCreateDialog(id); // use a default dialog.
    	}
    	return dialog;
    }
    
}
